﻿/*
 * telegrammonitor.cpp
 *
 *  Created on: 2017年3月3日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_OS_PROTOCOL DM_API_EXPORT

#include <dm/os/protocol/telegrammonitor.hpp>
#include <dm/datetime.hpp>
#include <iostream>

using namespace std;

namespace dm{
namespace os{
namespace protocol{

CTelegramMonitor::CTelegramMonitor():CTelegramMgr(),m_p(m_q->getCurPos()),m_raw(false),m_char(false),m_noData(false){
}

void CTelegramMonitor::onNew( const ringpos_t& /*pos*/,const info_t& info,const bool& overflow )const{
	if( overflow )
		cout <<"(of)";

	cout <<info.pid<<":";
	cout <<info.protocol.c_str();
	cout <<dm::CDateTime(info.ts).toString()<<':';
	if( info.type==info_t::Rx )
		cout <<"<RX ";
	else if( info.type==info_t::Tx )
		cout <<"<TX ";
	else
		cout <<"<RAW ";

	cout <<info.len;
	if( info.len>info_t::LenOfGram )
		cout <<"E";
	cout <<"> ";

	if( !m_noData ){
		for( dm::uint16 i=0;i<info_t::LenOfGram && i<info.len;++i ){
			if( m_char )
				printf("%c",info.gram[i]);
			else
				printf("%02X ",info.gram[i]);
		}
	}

	cout <<endl;
}

bool CTelegramMonitor::filter( const ringpos_t& /*pos*/,const info_t& info,const bool& /*overflow*/ )const{
	if( (m_raw && info.type!=info_t::Raw) || (!m_raw && info.type==info_t::Raw) )
		return true;
	return false;
}

void CTelegramMonitor::run(){
	info_t info;
	bool overflow;

	while( true ){
		if( m_q->waitAndCheckOver(m_p,overflow,info,1) )
			continue;
		if( !filter(m_p,info,overflow) )
			onNew(m_p,info,overflow);
		if( overflow )
			m_p = m_q->getCurPos();
	}
}

bool CTelegramMonitor::tryGet( info_t& info,bool& overflow ){
	return m_q->popAndCheckOver( m_p,overflow,info);
}

void CTelegramMonitor::get( info_t& info,bool& overflow ){
	m_q->waitAndCheckOver( m_p,overflow,info);
}
}
}
}
